package com.jckj.core.shiro;

import com.jckj.core.contants.SysContants;
import com.jckj.core.entity.SysUser;
import com.jckj.core.enums.UserStatus;
import com.jckj.core.enums.UserType;
import com.jckj.core.service.UserService;
import com.jckj.core.util.SpringContextHolder;
import com.jckj.core.util.StringUtils;
import com.jckj.core.vos.LoginUserVo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * <p>
 *     登录验证及权限查询
 * </p>
 * @author liuzhiyuan
 * @date 2018-01-02
 *
 */
public class MyRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyRealm.class);

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
        String loginName = (String)principalCollection.getPrimaryPrincipal();
        UserService userService = SpringContextHolder.getBean(UserService.class);
        List<String> userPermissions = userService.findUserPermission(loginName);
        auth.addStringPermissions(userPermissions);
        return auth;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)  authenticationToken;
        UserService userService = SpringContextHolder.getBean(UserService.class);
        SysUser sysUser = userService.findByLoginUsername(usernamePasswordToken.getUsername());
        if(sysUser==null){
            LOGGER.error("未找到相关账户");
            throw new UnknownAccountException("用户名或密码错误");
        }
        if(UserStatus.LOCKED.getCode().equals(sysUser.getUserStatus())){
            throw new LockedAccountException("账户已被停用");
        }
        String password = sysUser.getPassword();
        String inputPassword = StringUtils.encryPassword(String.valueOf(usernamePasswordToken.getPassword()), sysUser.getSalt());
        if(!password.equals(inputPassword)){
           throw new IncorrectCredentialsException("用户名或密码错误");
        }
        LoginUserVo loginUserVo = SpringContextHolder.getBean(LoginUserVo.class);
        loginUserVo.setLoginName(sysUser.getLoginName());
        loginUserVo.setName(sysUser.getUsername());
        loginUserVo.setId(sysUser.getId());
        if(UserType.ADMIN.getCode().equals(sysUser.getUserStatus())){
            loginUserVo.setAdmin(true);
        }else{
            loginUserVo.setAdmin(false);
        }
        return new SimpleAuthenticationInfo(usernamePasswordToken.getUsername(), usernamePasswordToken.getPassword(), getName());
    }
}
